// API 工具类
class ApiService {
  constructor() {
    this.baseURL = "https://api.petcommunity.com"; // 示例API地址
    this.timeout = 10000;
    this.defaultHeaders = {
      "Content-Type": "application/json",
    };
  }

  // 设置请求头
  setHeaders(headers) {
    this.defaultHeaders = { ...this.defaultHeaders, ...headers };
  }

  // 获取用户token
  getToken() {
    return wx.getStorageSync("token") || "";
  }

  // 设置token
  setToken(token) {
    wx.setStorageSync("token", token);
  }

  // 清除token
  clearToken() {
    wx.removeStorageSync("token");
  }

  // 通用请求方法
  request(options) {
    return new Promise((resolve, reject) => {
      const { url, method = "GET", data = {}, headers = {} } = options;

      wx.request({
        url: this.baseURL + url,
        method,
        data,
        header: { ...this.defaultHeaders, ...headers },
        timeout: this.timeout,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data);
          } else {
            reject(new Error(`请求失败: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        },
      });
    });
  }

  // GET请求
  get(url, params = {}) {
    const queryString = Object.keys(params)
      .map((key) => `${key}=${encodeURIComponent(params[key])}`)
      .join("&");

    const fullUrl = queryString ? `${url}?${queryString}` : url;

    return this.request({
      url: fullUrl,
      method: "GET",
    });
  }

  // POST请求
  post(url, data = {}) {
    return this.request({
      url,
      method: "POST",
      data,
    });
  }

  // PUT请求
  put(url, data = {}) {
    return this.request({
      url,
      method: "PUT",
      data,
    });
  }

  // DELETE请求
  delete(url) {
    return this.request({
      url,
      method: "DELETE",
    });
  }

  // 上传文件
  uploadFile(filePath, formData = {}) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: this.baseURL + "/upload",
        filePath,
        name: "file",
        formData,
        header: this.defaultHeaders,
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            resolve(data);
          } catch (e) {
            reject(new Error("上传失败"));
          }
        },
        fail: reject,
      });
    });
  }

  // 模拟API响应（用于开发阶段）
  mockResponse(data, delay = 500) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          message: "success",
          data,
        });
      }, delay);
    });
  }
}

// 创建API服务实例
const apiService = new ApiService();

// 帖子相关API
export const postAPI = {
  // 获取帖子列表
  getPosts: (params) => apiService.get("/posts", params),

  // 获取帖子详情
  getPostDetail: (id) => apiService.get(`/posts/${id}`),

  // 发布帖子
  createPost: (data) => apiService.post("/posts", data),

  // 点赞帖子
  likePost: (id) => apiService.post(`/posts/${id}/like`),

  // 取消点赞
  unlikePost: (id) => apiService.delete(`/posts/${id}/like`),

  // 评论帖子
  commentPost: (id, content) =>
    apiService.post(`/posts/${id}/comments`, { content }),

  // 获取评论列表
  getComments: (postId, params) =>
    apiService.get(`/posts/${postId}/comments`, params),
};

// 用户相关API
export const userAPI = {
  // 用户登录
  login: (code) => apiService.post("/auth/login", { code }),

  // 获取用户信息
  getUserInfo: () => apiService.get("/user/info"),

  // 更新用户信息
  updateUserInfo: (data) => apiService.put("/user/info", data),

  // 获取用户帖子
  getUserPosts: (userId, params) =>
    apiService.get(`/users/${userId}/posts`, params),
};

// 搜索相关API
export const searchAPI = {
  // 搜索帖子
  searchPosts: (keyword, params) =>
    apiService.get("/search/posts", { keyword, ...params }),

  // 搜索用户
  searchUsers: (keyword, params) =>
    apiService.get("/search/users", { keyword, ...params }),

  // 获取热门话题
  getHotTopics: () => apiService.get("/topics/hot"),
};

// 文件上传API
export const uploadAPI = {
  // 上传图片
  uploadImage: (filePath) => apiService.uploadFile(filePath),

  // 上传视频
  uploadVideo: (filePath) => apiService.uploadFile(filePath, { type: "video" }),
};

export default apiService;
